<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { showToast, showConfirmDialog, showSuccessToast } from 'vant';
import { useUserStore } from '@/store/user';
import YHeader from '@/components/YHeader.vue';
import { getCourseListByUserId, deleteCourse } from '@/api/classroom';
import { useRouter } from 'vue-router';

const router = useRouter();
const courseList = ref([]);
const userStore = useUserStore();
const userId = userStore.user.id || ''; // 获取用户ID

const loadCourseList = async () => {
  const res = await getCourseListByUserId(userId);
  courseList.value = res.data || [];
};

const onDelete = (id: number) => {
  showConfirmDialog({
    title: '提示',
    message: '确认删除该课程吗？',
  })
    .then(async () => {
      await deleteCourse(id);
      showSuccessToast('删除成功');
      loadCourseList();
    })
    .catch(() => {
      // 取消删除
    });
};

const toDetail = (id: number) => {
  router.push(`/classroom/detail?id=${id}`);
};

onMounted(() => {
  loadCourseList();
});
</script>

<template>
  <div class="course-list">
    <y-header title="课程管理" />


    <div class="list">
      <div v-for="item in courseList" :key="course.id" class="item">
        <div class="cover" @click="toDetail(course.id)">
          <van-image :src="item.coverImage" width="100%" height="80px" fit="cover" />
        </div>
        <div class="info">
          <div class="name">{{ item.name }}</div>
          <van-button type="danger" size="mini" @click="onDelete(course.id)">删除</van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.course-list {
  padding: 16px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.header-btn {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.item {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.cover {
  cursor: pointer;
}

.info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
}

.name {
  font-size: 16px;
  font-weight: 500;
}
</style>
